import { useState, useEffect } from 'react';
import Head from 'next/head';
import { 
  Upload, 
  Button, 
  Card, 
  Typography, 
  Slider, 
  Divider, 
  message, 
  Row, 
  Col,
  Image,
  Statistic,
  Collapse,
  Alert,
  Progress
} from 'antd';
import { 
  InboxOutlined, 
  DownloadOutlined,
  FileImageOutlined,
  DeleteOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import MainLayout from '../../components/layout/MainLayout';
import Compressor from 'compressorjs';

const { Title, Paragraph, Text } = Typography;
const { Dragger } = Upload;
const { Panel } = Collapse;

export default function ImageCompress() {
  const [fileList, setFileList] = useState([]);
  const [quality, setQuality] = useState(80); // 默认80%压缩质量
  const [isCompressing, setIsCompressing] = useState(false);
  const [progress, setProgress] = useState(0);
  const [previewImage, setPreviewImage] = useState('');
  const [originImage, setOriginImage] = useState('');
  const [originSize, setOriginSize] = useState(0);
  const [compressedSize, setCompressedSize] = useState(0);
  const [compressedImage, setCompressedImage] = useState(null);
  
  useEffect(() => {
    // 组件卸载时释放blob URL
    return () => {
      if (previewImage) URL.revokeObjectURL(previewImage);
      if (originImage) URL.revokeObjectURL(originImage);
      if (compressedImage) URL.revokeObjectURL(compressedImage);
    };
  }, []);
  
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('请上传图片文件!');
      return false;
    }
    
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('图片大小不能超过5MB!');
      return false;
    }
    
    // 预览原始图片
    const objectUrl = URL.createObjectURL(file);
    setOriginImage(objectUrl);
    setOriginSize(file.size);
    setCompressedSize(0);
    setPreviewImage('');
    setCompressedImage(null);
    
    return false; // 阻止自动上传
  };
  
  const handleFileChange = (info) => {
    // 仅保留最后上传的一张图片
    const fileList = info.fileList.slice(-1);
    setFileList(fileList);
  };
  
  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };
  
  const handleCompress = () => {
    if (fileList.length === 0) {
      message.warning('请先上传图片');
      return;
    }
    
    const file = fileList[0].originFileObj;
    setIsCompressing(true);
    setProgress(0);
    
    // 模拟进度
    const timer = setInterval(() => {
      setProgress(prevProgress => {
        const newProgress = prevProgress + 10;
        if (newProgress >= 90) {
          clearInterval(timer);
          return 90;
        }
        return newProgress;
      });
    }, 100);
    
    // 使用compressorjs压缩图片
    new Compressor(file, {
      quality: quality / 100,
      success(result) {
        clearInterval(timer);
        setProgress(100);
        setIsCompressing(false);
        
        // 预览压缩后的图片
        const objectUrl = URL.createObjectURL(result);
        setPreviewImage(objectUrl);
        setCompressedImage(objectUrl);
        setCompressedSize(result.size);
        
        message.success('图片压缩成功!');
      },
      error(err) {
        clearInterval(timer);
        setIsCompressing(false);
        setProgress(0);
        console.error(err);
        message.error('图片压缩失败，请重试');
      }
    });
  };
  
  const handleDownload = () => {
    if (!compressedImage) return;
    
    const link = document.createElement('a');
    link.href = compressedImage;
    
    // 从原文件名提取名称和扩展名
    const originalFileName = fileList[0].name;
    const lastDotIndex = originalFileName.lastIndexOf('.');
    const nameWithoutExt = originalFileName.substring(0, lastDotIndex);
    const extension = originalFileName.substring(lastDotIndex);
    
    link.download = `${nameWithoutExt}_compressed${extension}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };
  
  const handleClearAll = () => {
    setFileList([]);
    setOriginImage('');
    setPreviewImage('');
    if (compressedImage) URL.revokeObjectURL(compressedImage);
    if (originImage) URL.revokeObjectURL(originImage);
    setCompressedImage(null);
    setOriginSize(0);
    setCompressedSize(0);
  };
  
  return (
    <MainLayout>
      <Head>
        <title>图片压缩 - 在线工具平台</title>
        <meta name="description" content="在线压缩图片，减小文件大小，保持合理的图像质量" />
      </Head>
      
      <div className="page-header">
        <Title>图片压缩</Title>
        <Paragraph>
          压缩图片以减小文件大小，节省存储空间并加快网页加载速度
        </Paragraph>
      </div>
      
      <Row gutter={[24, 24]}>
        <Col xs={24} md={12}>
          <Card title="上传图片" className="upload-card">
            <Dragger 
              fileList={fileList}
              beforeUpload={beforeUpload}
              onChange={handleFileChange}
              accept="image/*"
              showUploadList={false}
            >
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽图片到此区域</p>
              <p className="ant-upload-hint">
                支持JPG、PNG、WEBP等常见图片格式，最大5MB
              </p>
            </Dragger>
            
            {fileList.length > 0 && (
              <div className="file-info">
                <FileImageOutlined /> {fileList[0].name} ({formatFileSize(originSize)})
                <Button 
                  type="text" 
                  danger 
                  icon={<DeleteOutlined />} 
                  onClick={handleClearAll}
                />
              </div>
            )}
          </Card>
          
          <Card title="压缩设置" className="options-card">
            <div className="option-row">
              <div className="option-label">压缩质量:</div>
              <Slider
                min={0}
                max={100}
                value={quality}
                onChange={value => setQuality(value)}
                marks={{
                  0: '低',
                  50: '中',
                  100: '高'
                }}
              />
              <div className="quality-value">{quality}%</div>
            </div>
            
            <Alert
              message="质量说明"
              description="较低的质量可以获得更小的文件大小，但可能会影响图像清晰度。建议使用60-80%的质量获得平衡的效果。"
              type="info"
              showIcon
              icon={<InfoCircleOutlined />}
            />
            
            <div className="action-container">
              <Button 
                type="primary" 
                size="large" 
                onClick={handleCompress}
                loading={isCompressing}
                disabled={fileList.length === 0}
                block
              >
                开始压缩
              </Button>
            </div>
            
            {isCompressing && (
              <Progress percent={progress} status="active" />
            )}
          </Card>
        </Col>
        
        <Col xs={24} md={12}>
          <Card title="预览与结果" className="preview-card">
            {originImage && (
              <div className="image-preview-container">
                <div className="preview-item">
                  <div className="preview-title">原始图片</div>
                  <div className="image-container">
                    <Image
                      src={originImage}
                      alt="原始图片"
                      style={{ maxWidth: '100%', maxHeight: '300px' }}
                    />
                  </div>
                  <div className="image-size">
                    大小: {formatFileSize(originSize)}
                  </div>
                </div>
                
                {previewImage && (
                  <div className="preview-item">
                    <div className="preview-title">压缩后</div>
                    <div className="image-container">
                      <Image
                        src={previewImage}
                        alt="压缩后图片"
                        style={{ maxWidth: '100%', maxHeight: '300px' }}
                      />
                    </div>
                    <div className="image-size">
                      大小: {formatFileSize(compressedSize)}
                    </div>
                  </div>
                )}
              </div>
            )}
            
            {!originImage && (
              <div className="empty-preview">
                <FileImageOutlined />
                <p>上传图片后预览</p>
              </div>
            )}
            
            {compressedImage && (
              <div className="compression-result">
                <Row gutter={[16, 16]}>
                  <Col span={8}>
                    <Statistic
                      title="压缩前"
                      value={formatFileSize(originSize)}
                      valueStyle={{ color: '#cf1322' }}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="压缩后"
                      value={formatFileSize(compressedSize)}
                      valueStyle={{ color: '#3f8600' }}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="压缩率"
                      value={`${Math.round((1 - compressedSize / originSize) * 100)}%`}
                      valueStyle={{ color: '#3f8600' }}
                    />
                  </Col>
                </Row>
                
                <Button
                  type="primary"
                  icon={<DownloadOutlined />}
                  onClick={handleDownload}
                  style={{ marginTop: 16 }}
                  block
                >
                  下载压缩图片
                </Button>
              </div>
            )}
          </Card>
        </Col>
      </Row>
      
      <Divider />
      
      <Collapse className="help-container">
        <Panel header="使用说明" key="1">
          <Paragraph>
            <ol>
              <li>点击上传区域或将图片拖拽到上传区域选择要压缩的图片</li>
              <li>调整压缩质量滑块，较低的质量可获得更小的文件大小</li>
              <li>点击"开始压缩"按钮进行压缩</li>
              <li>压缩完成后，可以预览压缩前后的效果并下载压缩后的图片</li>
            </ol>
          </Paragraph>
        </Panel>
        <Panel header="常见问题" key="2">
          <Paragraph>
            <strong>Q: 压缩后的图片质量会下降吗？</strong><br />
            A: 是的，压缩是通过降低图片质量来减小文件大小的。您可以通过调整压缩质量来平衡大小和质量。<br /><br />
            
            <strong>Q: 图片压缩是在本地完成还是需要上传到服务器？</strong><br />
            A: 所有处理都在您的浏览器中完成，无需上传到服务器，保证您的隐私安全。<br /><br />
            
            <strong>Q: 支持哪些图片格式？</strong><br />
            A: 支持大多数常见图片格式，如JPG、PNG、WEBP等。
          </Paragraph>
        </Panel>
      </Collapse>
    </MainLayout>
  );
} 